import {
	domain
} from '@/utils/domain.js';

function service(options = {}, method, data = {}, type) {
	let token = uni.getStorageSync('token') || "";
	options.url = `${domain}${options.url}`;
	options.timeout = options.timeout || 90 * 1000;
	//配置请求头
	options.header = {
		'content-type': options.url.includes('/login')?'application/x-www-form-urlencoded':'application/json',
	};
	if (token) {
		options.header['Authorization'] = token;
	}
	options.method = method || 'post';

	options.data = data;
	return new Promise((resolved, rejected) => {
		//成功
		options.success = (res) => {
			let code = res.data.code;
			if (+code == 200) { //请求成功
				resolved(res.data);
			} else if (code == 401) {
				uni.clearStorageSync();
				uni.reLaunch({
					url: '/pages/login/index'
				})
				uni.showToast({
					icon: 'none',
					duration: 4000,
					title: '请登录~'
				})
			} else {
				uni.showToast({
					icon: 'none',
					duration: 4000,
					title: `${res.data.message}`
				})
				rejected(res.data); //错误
			}
		}
		//错误
		options.fail = (err) => {
			if (err.errMsg == 'request:fail timeout') {
				uni.showToast({
					title: '请求超时，请稍后重试!',
					duration: 4000,
					icon: "none"
				});
			} else if (err.errMsg == 'request:fail ') {
				uni.showToast({
					title: '网络异常，请检查网络!',
					duration: 4000,
					icon: "none"
				});
			}
			rejected(err); //错误
		}
		uni.request(options);

	})
}
export default service;